const Core = require('@alicloud/pop-core')
const _vms = module.exports

_vms.send = async (mobile, clientInfo) => {
    if (!_.trim(mobile)) throw new Error('手机号不能为空')
    if (!helper.isCellPhone(mobile)) throw new Error('手机号格式不正确')
    // if (!clientInfo.sign_name) throw new Error('语音签名不能为空')
    if (!clientInfo.template_code) throw new Error('语音模板不能为空')

    // 发送短信
    let templateParam = JSON.stringify(clientInfo.content)

    //设置参数
    let params = {
        RegionId: clientInfo['region_id'] || 'default',
        CalledNumber: mobile,
        TtsCode:clientInfo.template_code,
        CalledShowNumber: clientInfo.sign_name || '',
        TtsParam: templateParam,
    }

    let client = new Core({
        accessKeyId: clientInfo.app_key,
        accessKeySecret: clientInfo.app_secret,
        endpoint: 'https://dyvmsapi.aliyuncs.com',
        apiVersion: '2017-05-25'
    });

    let clientResult = await new Promise((resolve, reject) => {
        client.request('SingleCallByTts', params, {method: 'POST'}).then((result) => {
            resolve({
                StatusCode: 200,
                ...result,
            })
        }, (ex) => {
            log4js.error(ex);
            resolve({
                StatusCode: 500,
                ErrorCode: 'Bad Error!',
                ErrorMessage: ex.message || '',
            })
        })
    })

    if (clientResult.StatusCode !== 200) {
        throw new Error(clientResult.ErrorMessage || '')
    }

    return { ...clientResult }
}
